package cn.edu360.day06;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	final static String KEY = "天王盖地虎";

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		try {
			ServerSocket socket = new ServerSocket(8888);
			System.out.println("服务端开启");
			while (true) {
				Socket accept = socket.accept();
				System.out.println("建立连接");
				ObjectInputStream ois = new ObjectInputStream(accept.getInputStream());
				String ret = (String) ois.readObject();
				// 获取输出流
				ObjectOutputStream oos = new ObjectOutputStream(accept.getOutputStream());
				if (KEY.equals(ret)) {
					oos.writeObject("宝塔镇河妖");
					oos.flush();
					// jar文件路径
					String path = (String) ois.readObject();
					// 接受jar文件
					FileOutputStream fos = new FileOutputStream(path);
					byte[] b = new byte[1024];
					int line = 0;
					while ((line = ois.read(b)) != -1) {
						fos.write(b,0, line);
					}
					fos.close();
					// 接受comd
					String comd = (String) ois.readObject();
					// 执行程序
					String value = Util.runJar(comd);
					oos.writeObject(value);
					oos.flush();
				} else {
					oos.writeObject("镇压不住！....");
					oos.flush();
				}
				accept.shutdownInput();
				accept.shutdownOutput();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
